package middleware

import (
	"go_gin_gorm_oceanlearn_study/common"
	"go_gin_gorm_oceanlearn_study/model"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取authorization header
		tokenString := c.GetHeader("Authorization")

		// 验证格式
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {  //如果tokenString为空或不以Bearer开头
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"}) //权限不足
			c.Abort() //将本次请求抛弃
			return
		}

		//提取token有效部位
		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString) // 从tokenString中解析出claims并返回
		if err != nil || !token.Valid {  //如果解析失败或者解析得到的token无效
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"}) //权限不足
			c.Abort() //将本次请求抛弃
			return
		}

		// 验证通过，获取claim 中的userId
		userId := claims.UserId
		DB := common.GetDB()
		var user model.User
		DB.First(&user, userId)

		// 用户不存在
		if user.ID == 0 { 
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"}) //权限不足
			c.Abort() //将本次请求抛弃
			return
		}

		//用户存在 则将用户信息写入上下文
		c.Set("user", user)

		c.Next()
	}
}